package com.manong.config.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.manong.utils.Result;
import com.manong.utils.ResultCode;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author 李茂鑫
 * @Date 2025/1/13 15:23
 * @Descripition  认证用户无权限访问处理器
 */
@Component
public class CustomerAccessDeniedHandler implements AccessDeniedHandler {
    //AccessDeniedHandler接口，用于处理用户在尝试访问没有权限的资源时的操作。
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        //handle方法在用户请求一个没有权限访问的资源时触发，并且返回一个JSON格式的错误响应，告知用户他们没有访问该资源的权限。
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream=response.getOutputStream();
        String result= JSON.toJSONString(Result.error().code(ResultCode.No_AUTH).message("无权限访问，请联系管理员"), SerializerFeature.DisableCircularReferenceDetect);
        //SerializerFeature.DisableCircularReferenceDetect：禁用循环引用检测，以避免在序列化过程中遇到对象循环引用的问题。
        outputStream.write(result.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();

    }
}
